package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.pojo.MenuBusiness;
import com.zhentao.pojo.MenuUser;
import com.zhentao.service.MenuUserService;
import com.zhentao.mapper.MenuUserMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【menu_user】的数据库操作Service实现
* @createDate 2025-07-01 14:58:38
*/
@Service
public class MenuUserServiceImpl extends ServiceImpl<MenuUserMapper, MenuUser>
    implements MenuUserService{

    @Override
    public List<MenuUser> getMenuTree() {
        // 查询所有菜单
        List<MenuUser> allMenus = baseMapper.selectList(null);

        // 找出顶级菜单 (parentid = 0)
        List<MenuUser> rootMenus = allMenus.stream()
                .filter(menu -> menu.getParentid() == 0)
                .collect(Collectors.toList());

        // 递归构建树形结构
        for (MenuUser menu : rootMenus) {
            menu.setChildren(getChildren(menu.getId(), allMenus));
        }

        return rootMenus;
    }

    @Override
    public List<MenuUser> getMenuByRole(Integer roleId) {
        // 实际项目应根据角色ID查询关联菜单
        // 这里简化处理，返回所有菜单
        return getMenuTree();
    }

    /**
     * 递归获取子菜单
     */
    private List<MenuUser> getChildren(Integer parentId, List<MenuUser> allMenus) {
        List<MenuUser> children = new ArrayList<>();
        for (MenuUser menu : allMenus) {
            if (menu.getParentid().equals(parentId)) {
                menu.setChildren(getChildren(menu.getId(), allMenus));
                children.add(menu);
            }
        }
        return children;
    }

}




